package com.hongri.recyclerview.webview;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import android.webkit.JavascriptInterface;
import com.hongri.recyclerview.utils.Logger;

/**
 * Created by zhongyao on 2017/2/13.
 */

public interface JSBridge {
    String TAG = "JSBridge";
    String RESULT_EMPTY = "{}";

    @JavascriptInterface
    String loadUrl(String var1);

    @JavascriptInterface
    String getGeolocation(String var1);

    public static final class JSPoxy implements JSBridge {
        private static final Object EMPTY = new SimpleJSBridge();
        private Map<String, Object> map = new HashMap();

        public JSPoxy() {
            Method[] arr$ = JSBridge.class.getDeclaredMethods();
            int len$ = arr$.length;

            for(int i$ = 0; i$ < len$; ++i$) {
                Method method = arr$[i$];
                this.map.put(method.getName(), EMPTY);
            }

        }

        public void addObjects(Object[] objs) {
            Object[] arr$ = objs;
            int len$ = objs.length;

            for(int i$ = 0; i$ < len$; ++i$) {
                Object obj = arr$[i$];
                Method[] arr$1 = obj.getClass().getDeclaredMethods();
                int len$1 = arr$1.length;

                for(int i$1 = 0; i$1 < len$1; ++i$1) {
                    Method method = arr$1[i$1];
                    String name = method.getName();
                    if(this.map.get(name) != null) {
                        this.map.put(name, obj);
                    }
                }
            }

        }

        private String execute(String name, String params) {
            Object obj = this.map.get(name);
            if(obj != null && obj != EMPTY) {
                Logger.d(TAG+ "JS调用了" + name + "方法");

                try {
                    Method e = obj.getClass().getDeclaredMethod(name, new Class[]{String.class});
                    return (String)e.invoke(obj, new Object[]{params});
                } catch (Exception var5) {
                    var5.printStackTrace();
                }
            } else {
                Logger.e(TAG+ "JS没有实现" + name + "方法");
            }

            return "{}";
        }

        @Override
        @JavascriptInterface
        public String loadUrl(String params) {
            return this.execute("loadUrl", params);
        }

        @Override
        @JavascriptInterface
        public String getGeolocation(String params) {
            return this.execute("getGeolocation", params);
        }
    }
}
